package stephen.com.controller.user;

import stephen.com.constant.Const;
import stephen.com.controller.BaseServlet;
import stephen.com.model.User;
import stephen.com.service.UserService;
import stephen.com.service.impl.UserServiceImpl;
import stephen.com.utils.CodeUtil;
import stephen.com.utils.EmailUtil;
import stephen.com.utils.MailUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/*")
public class LoginServlet extends BaseServlet {
	private UserService userService = new UserServiceImpl();

	public void login(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String username = req.getParameter("username");
			String password = req.getParameter("password");
			String remember = req.getParameter("remember");
			System.out.println(username);
			System.out.println(password);
			System.out.println(remember);

			if ( null != username && null != password ) {
				User exitUser = userService.findUserByName(username);
				if ( null != exitUser ) {
					//				System.out.println("1111111111");
					if ( password.equals(exitUser.getPassword()) ) {
						//勾选记住我
						if ( null != remember ) {
							//cookie名：userInfo来标记用户账号
							Cookie cookie = new Cookie("userCookie", username);
							cookie.setMaxAge(Const.MAX_COOKIE_TIME);
							cookie.setPath("/");
							resp.addCookie(cookie);
						}
						//					System.out.println("22222222222222");
						//登录后不用转发跳转，用重定向
						//防止转发后的页面被刷新时，重复提交登录页面的数据
						System.out.println("登录成功！");

						//更新登录时间
						userService.updateLoginTime(exitUser.getId());

						req.getSession().setAttribute("userId", exitUser.getId());
                        req.getSession().setMaxInactiveInterval(Const.MAX_SESSION_TIME);

						resp.sendRedirect(req.getContextPath() + "/view/home");
						return;
					}
				}
			}
			resp.sendRedirect(req.getContextPath() + "/view/index");
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void loginOut(HttpServletRequest req, HttpServletResponse resp) {
		try {
			Cookie[] cookies = req.getCookies();
			if ( null != cookies && cookies.length > 0 ) {
				for ( Cookie c : cookies ) {
					if ( "userCookie".equals(c.getName()) ) {
						c.setMaxAge(0);
						c.setPath("/");
						resp.addCookie(c);
						break;
					}
				}
			}

			resp.sendRedirect(req.getContextPath() + "/");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void register(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String email = req.getParameter("email");
			String username = req.getParameter("username");
			String password = req.getParameter("password");
			String confirmedPassword = req.getParameter("confirmedPassword");
			//校验数据的合法性
			if ( EmailUtil.checkEmail(email) ) {
				if ( null != username && null != password ) {
					if ( password.equals(confirmedPassword) ) {
						//两次密码一致
						User userByEamil = userService.findUserByEmail(email);
						if ( null == userByEamil ) {
							//先判断邮箱是否重复
							User userByName = userService.findUserByName(username);
							if ( null == userByName ) {
								//数据库中没有与注册用户名同名，则可以注册
								userService.addUser(email, username, password);
								//注册成功，（把regErrorMsg设为空串）跳转到登录页面
//								req.getSession().setAttribute("regErrorMsg", "");
								resp.sendRedirect(req.getContextPath() + "/view/index");
							} else {
								//注册的用户名已经存在于数据库中，不能被注册
								req.getSession().setAttribute("regErrorMsg", "该用户名已注册！");
								req.getRequestDispatcher("/register.jsp").forward(req, resp);
							}
						} else {
							//邮箱重复
							req.getSession().setAttribute("regErrorMsg", "该邮箱已被注册！");
							req.getRequestDispatcher("/register.jsp").forward(req, resp);
						}
					} else {
						//确认密码与密码不一致
						req.getSession().setAttribute("regErrorMsg", "请保持确认密码与密码一致！");
						req.getRequestDispatcher("/register.jsp").forward(req, resp);
					}

				} else {
					//用户名或密码未填写
					req.getSession().setAttribute("regErrorMsg", "请填写完整的用户名和密码！");
					req.getRequestDispatcher("/register.jsp").forward(req, resp);
				}

			} else {
				//邮箱未填写或格式不正确
				req.getSession().setAttribute("regErrorMsg", "请填写正确格式的邮箱！");
				req.getRequestDispatcher("/register.jsp").forward(req, resp);
			}
			req.getSession().setAttribute("regErrorMsg", "");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	public void sendCode(HttpServletRequest req, HttpServletResponse resp) {
		try {
			//设置请求头，发送text/html数据流
			resp.setHeader("Content-Type", "application/x-www-form-urlencoded");
			//获取邮箱
			String email = req.getParameter("email");
			//获取会话域
			HttpSession session = req.getSession();
//			System.out.println("进到sendCode了！");

			//验证邮箱的合法性
			if ( EmailUtil.checkEmail(email) ) {
				//再验证邮箱是否存在于数据库中即可
				User userByEmail = userService.findUserByEmail(email);
				System.out.println(null == userByEmail);

				if ( null != userByEmail ) {
					//一开始先判断session里面有没有code（看看是否已经发送过验证码）
					Object obj = session.getAttribute(email);
					//未发送过或者验证码已过期
					if ( null == obj ) {
						try {
							//邮件标题
							String title = "您正在进行【小标交友】项目的重置密码操作！";
							//获取验证码
							String code = CodeUtil.createRandomCode();
							//邮件内容
							String content = "您的验证码是：" + code;
							//把code放进session里
							session.setAttribute("Code", code);
							//设置会话保质期
							session.setMaxInactiveInterval(Const.MAX_CODE_TIME);
							//发送邮件
							MailUtil.send(email, title, content, MailUtil.UNICODE);
						} catch (Exception e) {
							e.printStackTrace();
						}
						//编辑响应后的输出内容
						resp.getWriter().write("验证码发送成功！请注意查收！");
					} else {
						resp.getWriter().write("验证码已发送到邮箱！");
					}
				} else {
					resp.getWriter().write("该邮箱未注册，请先注册！");
				}
			} else {
				resp.getWriter().write("请输入正确的邮箱格式！");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void resetPassword(HttpServletRequest req, HttpServletResponse resp) {
		try {
			String email = req.getParameter("email");
			String code = req.getParameter("code");
			String newPassword = req.getParameter("newPassword");
			HttpSession session = req.getSession();

			//先验证邮箱格式
			if ( EmailUtil.checkEmail(email) ) {
				//再验证邮箱是否存在于数据库中
				User userByEmail = userService.findUserByEmail(email);
				if ( null != userByEmail ) {
					Object obj = session.getAttribute("Code");
					if ( null != obj ) {
						String emailCode = obj.toString();
						if ( emailCode.equals(code) ) {
							//可以重置密码
							User user = userService.findUserByEmail(email);
							if ( null != user ) {
								userService.resetPassword(user.getId(), newPassword);
								resp.sendRedirect(req.getContextPath() + "/view/index");
								return;
							}
						}
					}

				}
			}
			//其余情况都是重置失败
			req.getSession().setAttribute("forgetErrorMsg", "密码重置失败!");
			resp.sendRedirect(req.getContextPath() + "/view/forget");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
